﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace LogViewApp.Web
{
    public partial class _Default : System.Web.UI.Page
    {
        public string ContainerUrl;
        public string ContainerName;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    //this.EnsureContainerExists();
                    var account = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
                    var blobs = account.CreateCloudBlobClient();

                    CreateSilverlightPolicy(blobs);

                    ContainerName = Guid.NewGuid().ToString();

                    var container = blobs.GetContainerReference(ContainerName);
                    container.Create();

                    var sas = container.GetSharedAccessSignature(new SharedAccessPolicy()
                    {
                        Permissions = SharedAccessPermissions.Write,
                        SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromMinutes(10)
                    });

                    ContainerUrl = new UriBuilder(container.Uri) { Query = sas.TrimStart('?') }.Uri.AbsoluteUri;

                }
            }
            catch (System.Net.WebException we)
            {
                //status.Text = "Network error: " + we.Message;
                if (we.Status == System.Net.WebExceptionStatus.ConnectFailure)
                {
                   // status.Text += "<br />Please check if the blob storage service is running at " + ConfigurationManager.AppSettings["storageEndpoint"];
                }
            }
            catch (StorageException se)
            {
                Console.WriteLine("Storage service error: " + se.Message);
            }

        }


        private void CreateSilverlightPolicy(CloudBlobClient blobs)
        {
            blobs.GetContainerReference("$root").CreateIfNotExist();
            blobs.GetContainerReference("$root").SetPermissions(
                new BlobContainerPermissions()
                {
                    PublicAccess = BlobContainerPublicAccessType.Blob
                });
            var blob = blobs.GetBlobReference("clientaccesspolicy.xml");
            blob.Properties.ContentType = "text/xml";
            blob.UploadText(@"<?xml version=""1.0"" encoding=""utf-8""?>
                    <access-policy>
                      <cross-domain-access>
                        <policy>
                          <allow-from http-methods=""*"" http-request-headers=""*"">
                            <domain uri=""*"" />
                            <domain uri=""http://*"" />
                          </allow-from>
                          <grant-to>
                            <resource path=""/"" include-subpaths=""true"" />
                          </grant-to>
                        </policy>
                      </cross-domain-access>
                    </access-policy>");
        }
    }
}